package com.sjy.controller;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sjy.bean.Role;
import com.sjy.bean.User;
import com.sjy.dao.authdao;

@Controller
public class HomeController {
	@Autowired
	private authdao authdao;
	
	@RequestMapping("/main")
	public String main(Model model) {
		User user =getUserDetails();
		Set set = new HashSet();
		 List<Role> roles = user.getRoles();
		 for (Role role : roles) {
			 set.addAll(role.getAuthoritys());
		}System.out.println(set);
	model.addAttribute("authorities",set);
		
	return "index";
	}
	private  User getUserDetails() {
		SecurityContext ctx = SecurityContextHolder.getContext();   
		Authentication auth = ctx.getAuthentication(); 
		return (User)auth.getPrincipal();
	}
	@RequestMapping("/test")
	@ResponseBody
	public String test(Model model) {
		  String username;
		  /**
		   * Authentication对象除了getPrincipal()方法返回用户基本信息外，还有getAuthorities()
		   *      /// 方法可以返回List<GrantedAuthority>，
		   *   ///  即用户的权限相关信息，通常是一些角色信息
		   */
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if (principal instanceof UserDetails) {
			username = ((UserDetails)principal).getUsername();
	    } else {
	        username = principal.toString();
	    }

		
	return username;
	}
}
